import { Space, Button, message, Form, Image } from 'antd';
import ProCard from '@ant-design/pro-card';
import React, { useState, useRef, useEffect } from 'react';
import { getDvaApp, history, } from 'umi';
import ProForm, {
    ProFormText,
    ProFormCheckbox,
    ProFormTextArea,
    ProFormUploadButton,
} from '@ant-design/pro-form';
import type { ProFormInstance } from '@ant-design/pro-form';
import { PageContainer } from '@ant-design/pro-layout';
import $utils from '@/utils/utils';
import { noticeCreate } from '@/services/notice';
import { platformNames } from '@/utils/common';
import { uploadImg } from '@/services/company';

const Detail: React.FC = () => {

    // 解决无法调用dispatch
    const dispatch = getDvaApp()._store.dispatch;
    const formRef = useRef<ProFormInstance>();
    const [cur_id, setCur_id] = useState<string>();
    const [noticeDetail, setNoticeDetail] = useState<any>();

    const [noticeImg, setNoticeImg] = useState<string>('');
    const [showTips, setShowTips] = useState<boolean>(false);


    const l_state: any = history.location.state;
    if (!cur_id && !l_state) {
        history.push('/OperationsMange/Notice');
    }

    const id: string = l_state?.data?.id || '';
    //  同path更新,只更新state时，通过id重新请求数据
    if ((l_state && id) && (!cur_id || cur_id !== id)) {
        setCur_id(id);
    } else if (l_state && !id && cur_id !== id) {
        setCur_id('');
    }

    const isCreate: boolean = l_state?.status === 'create';


    // 快递公司列表
    useEffect(() => {
        if (!cur_id) {
            setNoticeDetail(undefined);
            formRef && formRef.current?.resetFields();
        }
        else {
            const num_data = {
                segment: l_state?.data?.segment,
                expressId: l_state?.data?.expressName,
            };
            setNoticeDetail(num_data);
            formRef && formRef.current?.resetFields();
            return;
        }
    }, [cur_id]);

    return (
        <PageContainer>
            {(isCreate || noticeDetail) && <ProCard style={{ marginTop: 8 }} gutter={8} >
                <ProForm
                    labelCol={{ span: 4 }}
                    wrapperCol={{ span: 16 }}
                    layout={"horizontal"}
                    formRef={formRef}
                    initialValues={isCreate ? undefined : noticeDetail}
                    onFinish={async (values) => {
                        const { platform, upload, ...others } = values;
                        let params = { ...others, platforms: platform.join(), image: noticeImg };
                        const msg = await noticeCreate(params);
                        if (msg.code === 0) {
                            message.success('新增成功', 1, () => {
                                // 设置当前tab对象
                                $utils.setNewTab(dispatch, { name: '通知管理', path: '/OperationsMange/Notice', isTopMenu: true });
                                history.push('/OperationsMange/Notice');
                            });
                        }
                    }}
                    submitter={{
                        render: (props, doms) => {
                            return [
                                <Space style={{ marginLeft: '16.66666667%' }}>
                                    <Button type="primary" htmlType="submit">保存</Button>
                                    <Button onClick={() => {
                                        // 设置当前tab对象
                                        $utils.setNewTab(dispatch, { name: '号段管理', path: '/OperationsMange/Notice', isTopMenu: true });
                                        history.push('/OperationsMange/Notice');
                                    }}>取消</Button>
                                </Space>
                            ]
                        }
                    }}
                >
                    <ProFormText
                        width={'md'}
                        name="title"
                        label={'通知标题'}
                        placeholder={'请输入标题(50字)'}
                        fieldProps={{
                            maxLength: 25
                        }}
                        rules={[
                            {
                                required: true,
                            },
                        ]}
                    />
                    <ProFormCheckbox.Group
                        name="platform"
                        label="接收终端"
                        rules={[
                            {
                                required: true,
                            },
                        ]}
                        options={platformNames}
                    />

                    <ProFormTextArea label="通知内容" name="content" placeholder={'请输入内容(200字)'} fieldProps={{ maxLength: 200 }} rules={[
                        {
                            required: true,
                        },
                    ]} />
                    <Form.Item label="通知图片" rules={[
                        { required: true, },
                    ]}>
                        <Space size="large" style={{ alignItems: 'flex-start' }}>
                            <Image width={120} src={noticeImg || ' '} />
                            <ProFormUploadButton
                                name="upload"
                                fieldProps={{
                                    name: 'file',
                                    listType: 'picture-card',
                                    showUploadList: false,
                                    beforeUpload: (file: File) => {
                                        const isJpgOrPng = file.type === 'image/jpg' || file.type === 'image/jpeg' || file.type === 'image/png';
                                        if (!isJpgOrPng) {
                                            message.error('仅支持上传JPG、JEP、PNG格式的图片');
                                        }


                                        if (file.size && (file.size / 1024 / 1024 > 2)) {
                                            message.error(`请上传2M内的文件。`);
                                            return false;
                                        }
                                        return true;
                                    },
                                    customRequest: async (options) => {
                                        const { file, onSuccess, onError } = options;

                                        const params = {
                                            image: file,
                                        };
                                        try {

                                            const msg = await uploadImg(params);
                                            console.log(msg);
                                            const url = msg.body.url;
                                            setNoticeImg(url);
                                            onSuccess && onSuccess(msg);
                                        } catch (err: any) {
                                            onError && onError({ method: 'POST', name: 'img', message: err });
                                        }
                                    }
                                }}
                                extra="仅支持上传JPG、JEPG、PNG格式，大小在2M以内"
                            />
                        </Space>
                        <div style={{ visibility: showTips ? 'initial' : 'hidden', color: 'red' }}>请上传图片</div>
                    </Form.Item>
                </ProForm>
            </ProCard>}
        </PageContainer>
    );
};

export default Detail;
